<template>
	<view v-if="visible" class="dui-appoint-date">
		<view class="dui-mask" @click="close"></view>
		<view class="dui-content">
			<view class="dui-title">
				<text class="">选择预约日期</text>
				<text class="dui-cancel-btn" @click="close">取消</text>
			</view>
			<view class="dui-date">
				<view class="dui-date-item" :class="{ active: dateActiveIndex == index }"
					v-for="(itmes, index) in reservation_datetime" :key="index" @click="chooseDate(itmes,index)">
					<view class="dui-date-str">{{formattedDate(itmes.date)}}</view>
					<view>{{calculateWeekday(itmes.date)}}</view>
				</view>
			</view>
			<view class="dui-title">选择预约时间段</view>
			<scroll-view class="uni-swiper-tab" scroll-y>
				<u-row gutter="16">
					<u-col span="4" v-for="(item, index) in timeSlots" :key="index">
						<view class="dui-time-period" @click="item.disabled?null:chooseTimePeriod(item, index)">
							<view class="dui-time-period-item" :class="{ active: timePeriodActiveIndex == index, disabled: item.disabled }">
								{{item.time_period}}
							</view>
						</view>
					</u-col>
				</u-row>
			</scroll-view>
			<view class="dui-btn" @click="confirm">确认</view>
		</view>
	</view>
</template>

<script>
	// import { data } from '../../../../uview-ui/libs/mixin/mixin';

	export default {
		emits: ['close', 'update:modelValue', 'confirm', 'input'],
		data() {
			return {
				dateActiveIndex: 0,
				dateList: [],
				timePeriodActiveIndex: -1,
				timePeriodList: [{
						time_period: '9:00-11:00'
					},
					{
						time_period: '11:00-13:00'
					},
					{
						time_period: '13:00-15:00'
					},
					{
						time_period: '15:00-17:00'
					},
					{
						time_period: '17:00-19:00'
					},
					{
						time_period: '19:00-21:00'
					}
				],
				timeSlots: [],
				XuanZeTime: {
					end: "",
					start: ""
				},
				reservationDateTime: [],
				startTime: '',
				endTime: '',
				visible: false,
				datelll: ''
			};
		},
		props: {
			dateRange: {
				type: Number,
				default: 7
			},
			timePeriodData: Array
		},
		created() {

		},
		methods: {
			inits(datas) {
				let that = this
				console.log('数据', datas)
				that.visible = true

				that.reservation_datetime = datas.reservation_datetime
				that.reservationDateTime = datas.reservationDateTime
				that.datelll = datas.reservationDateTime[0]
				that.startTime = datas.startTime
				that.endTime = datas.endTime

				//获取第一个日期的时间段显示
				that.timeSlots = datas.reservation_datetime[0].period

				//that.init();
			},
			init() {
				let that = this
				//that.generateTimeSlots();
			},

			// 将时间转为秒数（解决跨天问题）
			parseTime(timeStr) {
				const parts = timeStr.split(":")
				if (parts.length < 2 || parts.some(p => isNaN(p))) {
					console.error("Invalid time format:", timeStr)
					return NaN
				}
				const [h, m, s] = parts.map(Number)
				return h * 3600 + m * 60 + (s || 0)
			},

			// 秒数转时间格式
			formatSeconds(seconds) {
				const h = Math.floor(seconds / 3600) % 24
				const m = Math.floor((seconds % 3600) / 60)
				return `${h.toString().padStart(2, '0')}:${m.toString().padStart(2, '0')}`
			},

			// 把开始和结束直接每隔一小时拆分一个时间段
			generateTimeSlots() {
				let that = this
				that.timeSlots = []

				let start = that.parseTime(that.startTime)
				let end = that.parseTime(that.endTime)

				//console.log('1----1',that.startTime,that.endTime)

				if (isNaN(start) || isNaN(end)) return

				// 处理跨天
				if (end <= start) end += 86400 // 增加24小时

				// 对齐到整点
				start = Math.floor(start / 3600) * 3600

				while (start < end) {
					const slotEnd = Math.min(start + 3600, end)
					that.timeSlots.push({
						start: that.formatSeconds(start),
						end: that.formatSeconds(slotEnd)
					})
					start = slotEnd
				}
				//console.log('2---2', that.timeSlots)
			},
			calculateWeekday(dates) {
				this.errorMsg = ''
				const dateObj = new Date(dates)

				// 验证日期有效性
				// if (isNaN(dateObj.getTime())) {
				// 	this.errorMsg = '无效的日期格式'
				// 	this.weekdayResult = ''
				// 	return
				// }

				// 定义星期映射表（可扩展多语言）
				const weekdays = [
					'星期日', '星期一', '星期二',
					'星期三', '星期四', '星期五', '星期六'
				]

				// 获取星期索引
				const dayIndex = dateObj.getDay()

				// 处理结果
				//this.weekdayResult = weekdays[dayIndex]
				return weekdays[dayIndex] || '--'
			},
			formattedDate(datez) {
				const date = new Date(datez);
				const month = date.getMonth() + 1; // getMonth 返回的是0-11之间的数值
				const day = date.getDate();
				return `${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`;
			},






























			chooseDate(item, index) {
				let that = this
				console.log('选择的日期',item)
				that.timeSlots = item.period
				that.dateActiveIndex = index;
				that.datelll = item.date
				
				that.timePeriodActiveIndex = -1;
				that.XuanZeTime = {
					end: "",
					start: ""
				}
			},
			chooseTimePeriod(item, index) {
				let str = item.time_period;
				let arrs = str.split("-");
				console.log('选择时间段拆分',arrs)
				this.XuanZeTime = {
					start: arrs[0],
					end: arrs[1]
				}
				
				this.timePeriodActiveIndex = index;
			},
			close() {
				this.visible = false
			},
			confirm() {
				if (this.XuanZeTime.start == "") {
					uni.showToast({
						title: '请选择时间段',
						icon: 'none'
					})
				} else {
					this.$emit('confirm', {
						date: this.datelll,
						start_time: this.XuanZeTime.start,
						end_time: this.XuanZeTime.end
					})
					this.visible = false
				}

			}
		}
	};
</script>

<style lang="scss" scoped>
	$activeColor: #FF611E;

	.dui-appoint-date {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		z-index: 99999;

		.dui-mask {
			position: absolute;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
			background-color: rgba(0, 0, 0, 0.55);
		}

		.dui-content {
			position: absolute;
			bottom: 0;
			left: 0;
			width: 100%;
			padding: 50rpx 30rpx;
			box-sizing: border-box;
			animation: slide 0.35s ease;
			border-radius: 15rpx 15rpx 0 0;
			color: #222;
			background-color: #fff;

			.dui-title {
				position: relative;
				display: flex;
				align-items: center;
				width: 100%;
				padding-left: 12rpx;
				font-size: 34rpx;
				margin-bottom: 50rpx;

				&::before {
					content: '';
					position: absolute;
					top: 50%;
					left: 0;
					width: 10rpx;
					height: 30rpx;
					background-color: $activeColor;
					background: linear-gradient($activeColor, #fff);
					border-radius: 5rpx;
					transform: translateY(-50%);
				}

				.dui-cancel-btn {
					margin-left: auto;
					font-size: 30rpx;
					color: $activeColor;
				}
			}

			.dui-date {
				width: 100%;
				margin-bottom: 50rpx;
				white-space: nowrap;
				overflow-x: auto;

				&::-webkit-scrollbar {
					display: none;
				}

				.dui-date-item {
					display: inline-block;
					width: 31%;
					padding: 20rpx 0;
					margin-right: 20rpx;
					text-align: center;
					font-size: 26rpx;
					border-radius: 8rpx;
					border: 3rpx solid #f7f7f7;
					background-color: #f7f7f7;

					&.active {
						border-color: $activeColor;
						background-color: #fff;
					}

					.dui-date-str {
						font-size: 30rpx;
					}
				}
			}

			.uni-swiper-tab {
				max-height: 500rpx;
			}

			.dui-time-period {
				display: flex;
				flex-wrap: wrap;
				justify-content: space-between;
				width: 100%;
				margin-bottom: 16rpx;

				.dui-time-period-item {
					position: relative;
					display: flex;
					align-items: center;
					justify-content: center;
					width: 100%;
					height: 100rpx;
					border-radius: 8rpx;
					border: 3rpx solid #f7f7f7;
					background-color: #f7f7f7;

					&.active {
						border-color: $activeColor;
						background-color: #fff;
					}

					&.disabled {
						color: #aaa;
					}

					.dui-disabled-appoint-text {
						position: absolute;
						left: 50%;
						bottom: 6rpx;
						color: $activeColor;
						font-size: 18rpx;
						transform: translateX(-50%);
					}
				}
			}

			.dui-btn {
				display: flex;
				align-items: center;
				justify-content: center;
				width: 100%;
				height: 85rpx;
				border-radius: 60rpx;
				color: #fff;
				background-color: $activeColor;
			}
		}
	}

	@keyframes slide {
		0% {
			transform: translateY(100%);
		}
	}
</style>